<template>
  <div>
    <div class="detail-info" style="margin-top: 50px">
      <div class="form-item">
        <h4>基本信息</h4>
        <el-form :model="infoForm"  label-width="180px">
          <el-form-item label="分公司">
            <el-select v-model="infoForm.branchId" v-if="isBranch" style="width: 180px" @change="getDeptList" @visible-change="visibleChange" filterable>
              <el-option
                v-for="item in branchList"
                :label="item.branch_Name"
                :value="item.branch_Id">
              </el-option>
            </el-select>
            <el-input v-if="!isBranch" v-model="branchName" style="width: 220px" disabled></el-input>
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select v-model="infoForm.deptId" v-if="isBranch" style="width: 180px" filterable>
              <el-option
                v-for="item in deptList"
                :value="item.org_id"
                :label="item.org_name">
              </el-option>
            </el-select>
            <el-input v-if="!isBranch" v-model="orgName" style="width: 220px" disabled></el-input>
          </el-form-item>
          <!--<el-form-item label="分公司">-->
            <!--<el-input v-model="this.branchName" style="width: 220px" disabled></el-input>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="所属部门">-->
            <!--<el-input v-model="this.orgName" style="width: 220px" disabled></el-input>-->
          <!--</el-form-item>-->
          <el-form-item label="优惠券名称" required>
            <el-input v-model="infoForm.tname" style="width: 220px"></el-input>
          </el-form-item>
          <el-form-item label="金额" required>
            <el-input v-model="infoForm.tcost" style="width: 220px"></el-input>
          </el-form-item>
          <el-form-item label="满多少" required>
            <el-input v-model="infoForm.fulluse" style="width: 220px"></el-input> 可用
          </el-form-item>
          <el-form-item label="Logo选择" required>
            <el-upload
              class="avatar-uploader"
              :action="imgUrl"
              name="imageFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
              <img v-if="infoForm.imgUrl" :src="this.imgHost + '/' + infoForm.imgUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="参与类型" required>
            <el-radio-group v-model="infoForm.createType">
              <el-radio :label="1">商品</el-radio>
              <el-radio :label="2">品牌</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="所属品牌" v-show="infoForm.createType === 2" required>
            <el-select v-model="infoForm.type1" style="width: 150px" @change="checkType2(infoForm.type1)">
              <el-option
                v-for="item in productList1"
                :label="item.cateName"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="infoForm.type2" style="width: 150px" @change="checkType3(infoForm.type2)">
              <el-option
                v-for="item in productList2"
                :label="item.cateName"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="infoForm.brandId" style="width: 150px" filterable clearable>
              <el-option
                v-for="item in brandList"
                :label="item.brandName"
                :value="item.brandId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-item" v-show="infoForm.createType === 1">
        <h4>商品信息</h4>
        <div style="margin:20px">
          <el-col :span="2">
            <el-button type="primary" size="small" style="">
              <a style="text-decoration:none; color:#fff" href="/static/template/品牌现金券.xlsx">下载模板</a>
            </el-button>
          </el-col>
          <el-col :span="6" class="pinpai">
            <el-upload
              class="upload-demo"
              action="123"
              :before-upload="beforeUpload"
              :file-list="fileList"
              accept=".xlsx,.xls">
              <el-button :disabled="primaryDisabled" type="primary">导入EXCEL</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且只能上传一个文件</div>
            </el-upload>
          </el-col>
          <el-col :span="2">
            <el-button @click="simpleCheck">选择商品</el-button>
          </el-col>
        </div>
        <el-table
          :data="tableData"
          border
          tooltip-effect="dark"
          style="width: 100%">
          <el-table-column
            prop="hmpId"
            align="center"
            label="商品ID">
          </el-table-column>
          <el-table-column
            prop="hmpName"
            align="center"
            label="商品名称">
          </el-table-column>
          <el-table-column
            prop="hmpUnit"
            align="center"
            label="单位">
          </el-table-column>
          <el-table-column
            prop="hmpNorms"
            align="center"
            label="规格">
          </el-table-column>
          <el-table-column
            prop="hmpBuyPrice"
            align="center"
            label="系统售价">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="">
            <template scope="scope">
              <el-button @click="omit(scope.$index, scope.row)" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="form-item">
        <h4>备注</h4>
        <el-form label-width="180px">
            <el-input  type="textarea" placeholder="请设置活动说明" v-model="infoForm.remark" style="width: 500px"></el-input>
        </el-form>
      </div>
    </div>
    <div style="margin: 20px auto; width: 17%">
      <el-button @click="submit" type="success">提交</el-button>
      <el-button @click="cancel" type="danger">取消</el-button>
    </div>
    <!--选择单品弹窗-->
    <el-dialog class="dialog" title="选择商品" :visible.sync="dialogSimple">
      <el-form style="margin-top: 20px; overflow: hidden" :inline="true" :model="formSimple" class="demo-form-inline">
        <el-form-item label="商品分类">
          <el-select v-model="formSimple.type1" style="width: 150px" filterable clearable @change="checkType2(formSimple.type1)">
            <el-option
              v-for="item in productList1"
              :label="item.cateName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formSimple.type2" style="width: 150px" filterable clearable @change="checkType3(formSimple.type2)">
            <el-option
              v-for="item in productList2"
              :label="item.cateName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formSimple.type3" style="width: 150px" filterable clearable>
            <el-option
              v-for="item in productList3"
              :label="item.cateName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="formSimple.brand" style="width: 150px" filterable clearable>
            <el-option
              v-for="item in brandList"
              :label="item.brandName"
              :value="item.brandId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ID" placeholder="请输入商品ID">
          <el-input style="width: 100px" v-model="formSimple.ID"></el-input>
        </el-form-item>
        <el-form-item label="名称" placeholder="请查询的商品名称">
          <el-input style="width: 120px" v-model="formSimple.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="simpleList">搜索</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="lotAdd">批量添加</el-button>
      </div>
      <el-table
        :data="simpleData"
        v-loading="isLoading"
        height="200"
        ref="multipleTable"
        tooltip-effect="dark"
        border
        style="width: 100%"
        @select-all="handleSelectionChange"
        @selection-change="handleChange">
        <el-table-column
          type="selection"
          :selectable="isCheck"
          width="55">
        </el-table-column>
        <el-table-column
          prop="hmpId"
          label="商品ID"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="hmpName"
          label="商品名称"
          align="center"
          width="300">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="saleunit"
          label="单位"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="salenorm"
          label="规格"
          align="center"
          width="200">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="price"
          label="系统售价"
          align="center"
          width="150">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="">
          <template scope="scope">
            <el-button v-show="scope.row.name === 'add'" @click="add(scope.$index, scope.row, $event)" size="small">添加</el-button>
            <el-button v-show="scope.row.name === 'cancel'" @click="add(scope.$index, scope.row, $event)" size="small">撤销</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="Number(total)"
        style="padding-top:10px;text-align: right;">
      </el-pagination>
    </el-dialog>
  </div>
</template>
<script>
  import { getInfo, activity } from '../../../../../config/proxy.js'
  import { apiHost, apiURL } from '../../../../../config/settings.js'
  import { mapState } from 'vuex'
  import axios from 'axios'
  import mixins from '../../../../../components/mixins.vue'
  export default {
    mixins: [mixins],
    data () {
      return {
        deptList: [],
        visible: false,
        imgHost: '',
        // 基本信息
        infoForm: {
          brandId: '',
          createType: 1,
          type1: '',
          type2: '',
          branchId: '',
          deptId: '',
          tname: '',
          tcost: '',
          fulluse: '',
          imgUrl: '',
          remark: ''
        },
        // 商品信息
        fileList: [],
        fileUrl: '',
        tableData: [],
        primaryDisabled: false,
//        productData: [],
        // 选择单品弹窗
        dialogSimple: false,
        brandList: [],
        productList1: [],
        productList2: [],
        productList3: [],
        formSimple: {
          type1: '',
          type2: '',
          type3: '',
          brand: '',
          ID: '',
          name: ''
        },
//      选择单品表格
        isLoading: false,
        simpleData: [],
        total: '',
        page: 1,
        pageSize: 10,
//      选中项的集合
        all: []
      }
    },
    methods: {
      getDeptList (val) {
        if (this.visible === true) {
          this.infoForm.deptId = ''
        }
        var _data = {}
        this.branchList.forEach(item => {
          if (val === item.branch_Id) {
            _data.orgId = item.org_id
            this.infoForm.bid = item.org_id
          }
        })
        getInfo.department(_data, (res) => {
          if (res.message === 'ok') {
            if (val === 1) {
              this.deptList = []
              res.content.forEach(element => {
                if (element.org_name.indexOf('公司') === -1) {
                  this.deptList.push(element)
                }
              })
              this.matchDept()
            } else {
              this.deptList = res.content
              this.matchDept()
            }
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'error'
            })
          }
        })
      },  // 获取部门
      matchDept () { // 匹配 当前登录人的部门与部门列表
        for (let index = 0; index < this.deptList.length; index++) {
          const element = this.deptList[index]
          if (Number(this.infoForm.deptId) === Number(element.org_id)) {
            return
          } else {
            if (index === this.deptList.length - 1) {
              this.infoForm.deptId = ''
            }
          }
        }
      },
      visibleChange (val) {
        this.visible = val
      },
      handleAvatarSuccess (res, file) {
        this.infoForm.imgUrl = res.content.imageUrl
      },      // 上传图片
      beforeUpload (file) {
        let fd = new window.FormData()
        fd.append('file', file)
        fd.append('branchId', this.infoForm.branchId)
        axios({
          method: 'post',
          url: this.fileUrl,
          data: fd
        }).then(res => {
          console.log(res)
          if (res.data.code === 0 && res.data.content.length !== 0) {
            res.data.content.forEach((item, index) => {
              const newItem = {
                hmpId: item.hmpId,
                hmpName: item.hmpName,
                hmpUnit: item.saleunit,
                hmpNorms: item.salenorm,
                hmpBuyPrice: item.price
              }
              this.tableData.push(newItem)
            })
          } else {
            this.$message({
              showClose: true,
              message: res.data.message,
              type: 'success'
            })
          }
        }).catch(res => {
          this.$message({
            showClose: true,
            message: '上传失败',
            type: 'error'
          })
        })
        return true
      }, // 导入
      uploadSuccess (res, file, fileList) {
        console.log(res)
        if (res.message === 'ok') {
          this.tableData = res.content
          this.primaryDisabled = true
//          this.basicInfo.fileName = file.name
        } else {
          this.primaryDisabled = false
          this.fileList = []
          this.$message({
            showClose: true,
            message: '上传失败',
            type: 'error'
          })
        }
      },  // 上传文件
      removeFlie (file, fileList) {
        if (fileList.length === 0) {
          this.primaryDisabled = false
          this.tableData = []
        }
      },          // 删除文件
      omit (index, row) {
        this.tableData.splice(index, 1)
      },  // 删除
//    选择单品
      simpleCheck () {
        this.dialogSimple = true
        // 重置
        this.formSimple.ID = ''
        this.formSimple.name = ''
        this.formSimple.type1 = ''
        this.formSimple.type2 = ''
        this.formSimple.type3 = ''
        this.formSimple.brand = ''
        this.simpleData = []
        this.page = 1
        this.total = ''
      },
      simpleList () {
        this.isLoading = true
        const queryData = {
          branchId: this.infoForm.branchId,
          fourCate: this.formSimple.brand,
          page: this.page,
          pageSize: this.pageSize,
          hmpId: this.formSimple.ID,
          hmpName: this.formSimple.name,
          firstCate: this.formSimple.type1,
          secondCate: this.formSimple.type2,
          thirdCate: this.formSimple.type3,
          showType: [1],
          isUseCoupon: 1 // 是否使用优惠券
        }
        getInfo.searchProduct(queryData, (res) => {
          console.log(res, '商品列表')
          if (res.message === 'ok' && res.content.content !== null) {
            if (this.tableData.length !== 0) {
              for (var i = 0; i < res.content.content.length; i++) {
                let a = true
                for (var j = 0; j < this.tableData.length; j++) {
                  if (res.content.content[i].hmpId === this.tableData[j].hmpId) {
                    res.content.content[i].name = 'cancel'
                    a = false
                  } else {
                    res.content.content[i].name = 'add'
                  }
                  if (a === false) {
                    j = this.tableData.length
                  }
                }
              }
            } else {
              res.content.content.forEach(function (item, index) {
                item.name = 'add'
              })
            }
            this.isLoading = false
            this.simpleData = res.content.content
            this.total = res.content.count
          } else if (res.message === 'ok' && res.content.content === null) {
            this.total = ''
            this.isLoading = false
          } else {
            this.$message({
              showClose: true,
              message: '查询单品失败',
              type: 'error'
            })
            this.total = ''
            this.isLoading = false
          }
        })
      },
      checkType2 (val) {
        this.productList2 = []
        this.formSimple.type2 = ''
        this.infoForm.type2 = ''
        this.formSimple.brand = ''
        this.infoForm.brandId = ''
        getInfo.getCate({pid: val}, (res) => {
          if (res.message === 'ok') {
            this.productList2 = res.content
          }
        })
      },
      checkType3 (val) {
        this.productList3 = []
        this.formSimple.type3 = ''
        this.infoForm.brandId = ''
        getInfo.getCate({pid: val}, (res) => {
          if (res.message === 'ok') {
            this.productList3 = res.content
          }
        })
        getInfo.getBrand({cateId: val}, (res) => {
          if (res.message === 'ok') {
            this.brandList = res.content
          }
        })
      },
      handleChange (all) {
        this.all = all
      },
      handleSelectionChange (all) {
        this.all = all
      },
      add (index, row, event) {
        if (event.target.innerText === '添加') {
          row.name = 'cancel'
          this.$refs.multipleTable.toggleRowSelection(row, true)
          if (this.tableData.indexOf(row) === -1) {
            const newItem = {
              hmpId: row.hmpId,
              hmpName: row.hmpName,
              hmpUnit: row.saleunit,
              hmpNorms: row.salenorm,
              hmpBuyPrice: row.price
            }
            this.tableData.unshift(newItem)
          }
        } else {
          row.name = 'add'
          this.$refs.multipleTable.toggleRowSelection(row, false)
          const index = this.tableData.indexOf(row)
          this.tableData.splice(index, 1)
        }
      },
      lotAdd () {
//      状态变为撤销
        this.simpleData.forEach((item1, index1) => {
          this.all.forEach(function (item, index) {
            if (item1.hmpId === item.hmpId) {
              item1.name = 'cancel'
            }
          })
        })
//      添加进去
        this.all.forEach((item, index) => {
          if (this.tableData.indexOf(item) === -1) {
            const newItem2 = {
              hmpId: item.hmpId,
              hmpName: item.hmpName,
              hmpUnit: item.saleunit,
              hmpNorms: item.salenorm,
              hmpBuyPrice: item.price
            }
            this.tableData.unshift(newItem2)
          }
        })
      },
      handleCurrentChange (val) {
        this.page = val
        this.simpleList()
      },
      isCheck (row, index) {
        return row.name === 'add'
      },
      cancel () {
        this.$store.dispatch('delTab', {id: 'ppq_add'})
      },  // 取消
      submit () {
        var regu = /^[1-9]\d*$/
        if (this.infoForm.tname === '' || this.infoForm.tcost === '' || this.infoForm.fulluse === '') {
          this.$message({
            showClose: true,
            message: '红色标记部分为必选项！',
            type: 'error'
          })
          return false
        }
        if (!regu.test(this.infoForm.fulluse)) {
          this.$message({
            showClose: true,
            message: '满多少金额不能含负，0，小数',
            type: 'error'
          })
          return false
        }
        if (!regu.test(this.infoForm.tcost)) {
          this.$message({
            showClose: true,
            message: '金额不能含负，0，小数',
            type: 'error'
          })
          return false
        }
        if (Number(this.infoForm.fulluse) <= Number(this.infoForm.tcost)) {
          this.$message({
            showClose: true,
            message: '满多少金额必须大于优惠券金额',
            type: 'error'
          })
          return false
        }
        if (this.infoForm.imgUrl === '') {
          this.$message({
            showClose: true,
            message: '请上传图片',
            type: 'error'
          })
          return false
        }
        if (this.infoForm.createType === 2 && this.infoForm.brandId === '') {
          this.$message({
            showClose: true,
            message: '请选择品牌',
            type: 'error'
          })
          return false
        }
        if (this.infoForm.createType === '1' && this.tableData.length === 0) {
          this.$message({
            showClose: true,
            message: '请选择商品',
            type: 'error'
          })
          return false
        }
        this.infoForm.products = this.tableData
        console.log(this.infoForm)
        activity.yhqhd.jcq.ppq_creation(this.infoForm, res => {
          console.log(res)
          if (res.message === 'ok') {
            this.$message({
              showClose: true,
              message: '创建成功',
              type: 'success'
            })
            this.$store.dispatch('delTab', {id: 'ppq_add'})
            this.$store.dispatch('ppqState', this.$store.state.updateState.ppqState + 1)
          } else {
            this.$message({
              showClose: true,
              message: '创建失败',
              type: 'error'
            })
          }
        })
      }   // 提交
    },
    computed: mapState({
      userName: function (state) {
        return state.user.info.user_name
      },
      orgName: function (state) {
        return state.user.info.parOrgName
      },
      orgId: function (state) {
        return state.user.info.or_org_id
      },
      branchName: function (state) {
        return state.user.info.branchId === 1 ? '总公司' : state.user.info.branchName
      },
      branchId: function (state) {
        return state.user.info.branchId
      },
      branchIdOld: function (state) {
        return state.user.info.branchOrgId
      }
    }),
    created () {
      this.infoForm.branchId = this.branchId
      this.infoForm.deptId = this.orgId
      this.infoForm.bid = this.branchIdOld
      this.infoForm.createUser = this.userName
      this.imgHost = apiHost.imgHost
      this.fileUrl = 'http://' + apiHost.newCms + ':20000' + apiURL.ppq_upload
      this.imgUrl = 'http://' + apiHost.newCms + ':20000' + '/fileUtils/upLoadImage'
      // 商品分类
      getInfo.getCate({pid: 0}, (res) => {
        if (res.message === 'ok') {
          this.productList1 = res.content
        }
      })
    },
    watch: {
      branchList (a, b) {
        this.getDeptList(this.infoForm.branchId)
      }
    }
  }
</script>
<style>
  .pinpai .el-upload-list {
    display: none;
  }
</style>
